use std::future::pending;
use std::mem;

use tokio::task::{JoinError, JoinHandle};
pub struct AbortOnDropHandle<T> {
    inner: JoinHandle<T>,
}

impl<T> Drop for AbortOnDropHandle<T> {
    fn drop(&mut self) {
        self.inner.abort();
    }
}

impl<T> From<JoinHandle<T>> for AbortOnDropHandle<T> {
    fn from(inner: JoinHandle<T>) -> Self {
        Self { inner }
    }
}
impl<T: Send + 'static> AbortOnDropHandle<T> {
    pub async fn join(mut self) -> Result<T, JoinError> {
        let handle: JoinHandle<T> = mem::replace(&mut self.inner, tokio::spawn(pending::<T>()));
        handle.await
    }
}
